package utils

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"micro-oauth/config"
	"mime"
	"strconv"
)

type MailMessage struct {
	ToUser 			string
	AuthCode 		string
	Subject 		string
	Domain		    string
	Account 		string
	Mail 		    string
	UserId          uint64
}

var emailConfig = config.LoadEmailConfig()

func SendEmail(to string, msg string, subject string) error {
	var mailDialer = gomail.NewDialer(
		emailConfig.SMTPHost, emailConfig.SMTPPort, emailConfig.Account, emailConfig.Pwd,
	)
	from := emailConfig.Account
	senderNick := mime.QEncoding.Encode("UTF-8", "合阔智云")
	from = fmt.Sprintf("%s <%s>", senderNick, from)

	m := gomail.NewMessage()
	m.SetHeader("From", from)
	m.SetHeader("To", to)
	if subject != "" {
		m.SetHeader("Subject", subject)
	}
	m.SetBody("text/html", msg)
	err := mailDialer.DialAndSend(m)
	return err
}

func SendHtmlEmail(msg *MailMessage) error {
	var mailDialer = gomail.NewDialer(
		emailConfig.SMTPHost, emailConfig.SMTPPort, emailConfig.Account, emailConfig.Pwd,
	)
	from := emailConfig.Account
	senderNick := mime.QEncoding.Encode("UTF-8", "合阔智云")
	from = fmt.Sprintf("%s <%s>", senderNick, from)

	m := gomail.NewMessage()
	m.SetHeader("From", from)
	m.SetHeader("To", msg.ToUser)
	if msg.Subject != "" {
		m.SetHeader("Subject", msg.Subject)
	}
	userId := strconv.Itoa(int(msg.UserId))
	content := `<!DOCTYPE html><html>`
	content += `<head>
				<meta charset="UTF-8">
				<title></title>
				<style type="text/css">
					body{
						width: 100%;
						margin: 0;
						margin-top: 50px;
						padding: 0;
						color: #333;
					}
					a{
						text-decoration: underline;
						color: #4A90E2;
					}
					a:hover{
						cursor: pointer;
					}
					.box{
						width: 50%;
						margin: 0 auto;
					}
					.reset-a{
						color: #9968FF;
		
					}
					#btn{
						background-color: #9968FF;
						width: 80px;
						height: 36px;
						line-height: 34px;
						font-size: 14px;
						color: #eee;
						border-radius: 5px;
					}
					
					</style>
				</head>`
	content += `<body>
					<div class="box">
						<h4>HWS账号修改密码验证</h4>
						<p>您的HWS账号<b>`+msg.Account+`</b> &nbsp;<b></b> 正在进行修改密码操作，请点击以下链
							接进行账号验证（30分钟内有效，过期后可重新发送）
						</p>
						<p>关系您的账号安全，如果修改密码操作不是您本人发起，请谨慎处理！</p>`
	content += `<a>http://`+msg.Domain+`/?code=`+msg.AuthCode+`&id=`+userId+`&mail=`+msg.Mail +`&enterType=reset</a>`

	content += 	`<h4>点击这里<a href="http://`+msg.Domain+`/#/?code=`+msg.AuthCode+`&id=`+userId+`&mail=`+msg.Mail+`&enterType=reset" class="reset-a">重置密码</a>后，可操作HWS账号（`+msg.Account+`）密码，</h4>
						<h4>是否继续？</h4>
					</div>
				</body>
			</html>`



	m.SetBody("text/html", content)
	err := mailDialer.DialAndSend(m)
	return err
}
